﻿#define _CRT_SECURE_NO_WARNINGS 1


#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
    int lastStoneWeightII(vector<int>& stones)
    {
        // 1. 准备⼯作
        int sum = 0;
        for (auto x : stones)
            sum += x;
        int n = stones.size(), m = sum / 2;
        // 2. dp
        vector<int> dp(m + 1);
        for (int i = 1; i <= n; i++)
            for (int j = m; j >= stones[i - 1]; j--)
                dp[j] = max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);
        // 3. 返回结果
        return sum - 2 * dp[m];
    }
};

int main()
{
    vector<int> stones = { 31, 26, 33, 21, 40 };

    cout << Solution().lastStoneWeightII(stones) << endl;

    return 0;
}


